package http;

import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.*;
import java.nio.file.Files;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;

/**
 * @package http
 * @Class Chrome
 * @Description 谷歌浏览器内核方式访问
 * @Author zhangxinhua
 * @Date 19-10-11 上午9:53
 */
public class Chrome {


    WebDriver webDriver ;
    @Before
    public void Setup(){
        ChromeOptions chromeOptions = new ChromeOptions();
        File chromeDriverPath = new File("/root/Downloads/chromedriver");
        System.setProperty("webdriver.chrome.driver", chromeDriverPath.getAbsolutePath());
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("--disable-gpu");
        //ubuntu浏览器中需要添加
        chromeOptions.addArguments("--no-sandbox");
        webDriver = new ChromeDriver(chromeOptions);
    }

    @Test
    public void getCookies(){
        BufferedReader bufferedReader;
        webDriver.get("https://juejin.im/timeline");


        try {
            File cookieFile = new File("csdn.cookie.txt");
            FileReader fileReader = new FileReader(cookieFile);
            bufferedReader = new BufferedReader(fileReader);

            String line;

            while ((line = bufferedReader.readLine()) != null){
                StringTokenizer stringTokenizer = new StringTokenizer(line, ";");
                while (stringTokenizer.hasMoreTokens()){

                    String name = stringTokenizer.nextToken();
                    String value = stringTokenizer.nextToken();
                    String domain = stringTokenizer.nextToken();
                    String path = stringTokenizer.nextToken();
                    Date expiry = null;
                    String dt;

                    if (!(dt = stringTokenizer.nextToken()).equals("null")){
                        expiry = new Date(dt);
                    }

                    boolean isSecure = new Boolean(stringTokenizer.nextToken()).booleanValue();
                    Cookie cookie = new Cookie(name, value,domain,path,expiry,isSecure);
                    webDriver.manage().addCookie(cookie);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        webDriver.get("https://juejin.im/post/5d9c531f6fb9a04e0b0da679");
        System.out.println(webDriver.getPageSource());
    }

    @Test
    public void writeCookies() {

        webDriver.get("https://passport.csdn.net/login?code=public");
        WebElement element = webDriver.findElement(By.xpath("//*[@id=\"app\"]/div/div/div[1]/div[2]/div[5]/ul/li[2]/a"));
        JavascriptExecutor js = (JavascriptExecutor) webDriver;
        Object o = js.executeScript("arguments[0].click();", element);
        webDriver.findElement(By.xpath("//*[@id=\"all\"]")).sendKeys("870775401@qq.com");
        webDriver.findElement(By.xpath("//*[@id=\"password-number\"]")).sendKeys("Qq15996779085csdn");

        /*if (webDriver.findElement(By.xpath("//*[@id=\"rememberMe\"]")).isSelected()){
            webDriver.findElement(By.xpath("//*[@id=\"rememberMe\"]")).click();
        }*/

        webDriver.findElement(By.xpath("//*[@id=\"app\"]/div/div/div[1]/div[2]/div[5]/div/div[6]/div/button")).click();

        File cookieFile = new File("csdn.cookie.txt");

        try {
            cookieFile.delete();
            cookieFile.createNewFile();
            FileWriter fileWriter = new FileWriter(cookieFile);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

            for (Cookie cookie:webDriver.manage().getCookies()){
                bufferedWriter.write((cookie.getName()+";"+
                        cookie.getValue()+";"+
                        cookie.getDomain()+";"+
                        cookie.getPath()+";"+
                        cookie.getExpiry()+";"+
                        cookie.isSecure()));
                bufferedWriter.newLine();
            }
            bufferedWriter.flush();
            bufferedWriter.close();
            fileWriter.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        webDriver.quit();
    }

    @Test
    public void takesScreenshotTest() {
        webDriver.get("https://blog.csdn.net/bpz31456/article/details/81875735");
        File source = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
        try {
            Files.copy(source.toPath(), new FileOutputStream(new File("/root/Downloads/test/1.png")));
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    @Test
    public void writeJuejinCookies() {

        webDriver.get("https://juejin.im/");
        WebElement element1 = webDriver.findElement(By.xpath("//*[@id=\"juejin\"]/div[2]/div/header/div/nav/ul/li[4]/span[1]"));
        element1.click();
       /* WebElement element = webDriver.findElement(By.xpath("//*[@id=\"app\"]/div/div/div[1]/div[2]/div[5]/ul/li[2]/a"));
        JavascriptExecutor js = (JavascriptExecutor) webDriver;
        Object o = js.executeScript("arguments[0].click();", element);*/
        webDriver.findElement(By.xpath("//*[@id=\"juejin\"]/div[1]/div[3]/form/div[2]/div[1]/div[1]/input")).sendKeys("870775401@qq.com");
        webDriver.findElement(By.xpath("//*[@id=\"juejin\"]/div[1]/div[3]/form/div[2]/div[1]/div[2]/input")).sendKeys("QQ15996779085");

        /*if (webDriver.findElement(By.xpath("//*[@id=\"rememberMe\"]")).isSelected()){
            webDriver.findElement(By.xpath("//*[@id=\"rememberMe\"]")).click();
        }*/

        webDriver.findElement(By.xpath("//*[@id=\"juejin\"]/div[1]/div[3]/form/div[2]/button")).click();
        webDriver.navigate().to("https://juejin.im/post/5d9d81fbf265da5bbe2a3116");
        webDriver.get("https://juejin.im/post/5da12a14f265da5b926bcd66");

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        /*WebElement element = webDriver.findElement(By.xpath("//*[@id=\"juejin\"]/div[2]/main/div/div/div/div/div/ul/li[2]/div/div/a/div/div/div[2]/a"));
        element.click();*/
        Set<String> windowHandles = webDriver.getWindowHandles();
        for (String windowHandle : windowHandles) {
            if (!windowHandle.equals(webDriver.getWindowHandle())) {
                //webDriver.switchTo().window(windowHandle);
            }
        }
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        WebElement digg = webDriver.findElement(By.cssSelector("#juejin > div.view-container > main > div > div.article-suspended-panel.article-suspended-panel > div.like-btn.panel-btn.like-adjust.with-badge"));
        JavascriptExecutor js = (JavascriptExecutor) webDriver;
        js.executeScript("arguments[0].click();",digg);
        //digg.click();
        //System.out.println(element.getText()+"点赞成功！");

        File source = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
        try {
            Files.copy(source.toPath(), new FileOutputStream(new File("/root/Downloads/test/1.png")));
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        File cookieFile = new File("csdn.cookie.txt");

        try {
            cookieFile.delete();
            cookieFile.createNewFile();
            FileWriter fileWriter = new FileWriter(cookieFile);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

            for (Cookie cookie:webDriver.manage().getCookies()){
                bufferedWriter.write((cookie.getName()+";"+
                        cookie.getValue()+";"+
                        cookie.getDomain()+";"+
                        cookie.getPath()+";"+
                        cookie.getExpiry()+";"+
                        cookie.isSecure()));
                bufferedWriter.newLine();
            }
            bufferedWriter.flush();
            bufferedWriter.close();
            fileWriter.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        webDriver.quit();
    }

    public static void main(String[] args) {
        Chrome chrome = new Chrome();
        //chrome.selenium("https://news.163.com/");
        chrome.selenium("https://juejin.im/post/5d9ec8b0518825651b1dffa3");
    }

    /**
     * selenium 解决数据异步加载问题
     * https://npm.taobao.org/mirrors/chromedriver/
     *
     * @param url
     */
    public void selenium(String url) {
        // 设置 chromedirver 的存放位置
        System.setProperty("webdriver.chrome.driver", "/root/Downloads/chromedriver");
        // 设置无头浏览器，这样就不会弹出浏览器窗口
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("--disable-gpu");
        //ubuntu浏览器中需要添加
        chromeOptions.addArguments("--no-sandbox");


        WebDriver webDriver = new ChromeDriver(chromeOptions);
        webDriver.get("https://juejin.im/");
        String cookieStr = "ab={}; _ga=GA1.2.342489954.1566199726; gr_user_id=accd433a-b338-4294-860d-27e04522b77d; auth=eyJ0b2tlbiI6ImV5SmhZMk5sYzNOZmRHOXJaVzRpT2lKb1RuVm1TRk5vTkdOMWVrc3pOM1ZrSWl3aWNtVm1jbVZ6YUY5MGIydGxiaUk2SWxvMFprbDNUelkwTldGYVUyVndlSE1pTENKMGIydGxibDkwZVhCbElqb2liV0ZqSWl3aVpYaHdhWEpsWDJsdUlqb3lOVGt5TURBd2ZRPT0iLCJjbGllbnRJZCI6MTU2ODc5NzIzMjE3OSwidXNlcklkIjoiNTllNTk5M2I2ZmI5YTA0NTI4NDU4ZDhjIn0=; auth.sig=FE6wQYkeuzO4MpTvD1WXUvlkphg; __51cke__=; MEIQIA_TRACK_ID=1Pcjt3CB6S9EHlCONfDecq52yfv; MEIQIA_VISIT_ID=1RxII1Z5wEnrrWBtQxHMPfOwNe9; __tins__20061455=%7B%22sid%22%3A%201570514922910%2C%20%22vd%22%3A%202%2C%20%22expires%22%3A%201570517727604%7D; __51laig__=2; _gid=GA1.2.944169928.1570611093; Hm_lvt_93bbd335a208870aa1f296bcd6842e5e=1570426343,1570440275,1570515473,1570697675; gr_cs1_a24a1ff4-955e-45db-9a7f-49334f15ab62=objectId%3A59e5993b6fb9a04528458d8c; gr_session_id_89669d96c88aefbc=bb47036c-b3d7-4efa-9fec-33f8ab2cb67d; gr_cs1_bb47036c-b3d7-4efa-9fec-33f8ab2cb67d=objectId%3A59e5993b6fb9a04528458d8c; gr_session_id_89669d96c88aefbc_bb47036c-b3d7-4efa-9fec-33f8ab2cb67d=true; QINGCLOUDELB=165e4274d6090771b096025ed82d52a1ab7e48fb3972913efd95d72fe838c4fb|XZ/lt|XZ/lt; Hm_lpvt_93bbd335a208870aa1f296bcd6842e5e=1570760118; _gat=1";
        /*String[] split = cookieStr.split(";");
        for (String cook : split) {
            String[] cookies = cook.split("=");
            Cookie cookie = new Cookie(cookies[0],cookies[1]);
            //webDriver.manage().addCookie(cookie);
        }*/
        System.out.println(webDriver.manage().getCookies());
        webDriver.get(url);
        // 获取到要闻新闻列表
        List<WebElement> webElements = webDriver.findElements(By.xpath("//*[@id=\"juejin\"]/div[2]/main/div/div[4]/div[1]"));
        JavascriptExecutor js = (JavascriptExecutor) webDriver;
        for (WebElement webElement : webElements) {
            js.executeScript("arguments[0].click();",webElement);
        }
        webDriver.close();
    }
}
